import request from './request'
import crypto from 'crypto'
export const postJson = (uri, params) => {
	//return request.post(uri, params).then(res => res.data);
	var obj = {
		headers: {
			"Content-Type": "application/json",
		}
	}
	return post(uri, params, obj)
}
export const post = (uri, params, obj = {}) => {
	//return request.post(uri, params).then(res => res.data);

	return new Promise((resolve, reject) => {
		request.post(uri, params, obj).then((res) => {
			const { data } = res;
			if (data.err_code) {
				reject(data.err_msg);
			} else {
				resolve(data.data || {});
			}
		}).catch((e) => {
			if (e.response?.status === 500) {
				reject('网络异常，请稍后再试');
			}
		})
	});
}

export const get = (uri, params, obj = {}) => {
	//return request.post(uri, params).then(res => res.data);

	return new Promise((resolve, reject) => {
		request.get(uri, { params }).then((res) => {
			const { data } = res;
			if (data.err_code) {
				reject(data.err_msg);
			} else {
				resolve(data.data || {});
			}
		}).catch((e) => {
			if (e.response?.status === 500) {
				reject('网络异常，请稍后再试');
			}
		})
	});
}

export const upload = (uri, params, headers = {}) => {
	return request.post(uri, params, {
		headers: {
			...headers,

			//'Content-Type': 'multipart/form-data',
			'Content-Type': null
		}
	}).then(res => res.data)
}

export const md5 = (string) => {
	return crypto.createHash('md5').update(string).digest('hex');
}

export const treeToList = (tree, list = []) => {
	tree.forEach((item) => {
		const { children } = item;
		if (children) {
			delete item.children;

			if (children.length) {
				list.push(item);
				return treeToList(children, list);
			}
		}
		list.push(item);
	});
	return list;
}

export const listToTree = (list, parentId = 0) => {
	return list.filter(item => item.parent_id === parentId).map(item => {
		const children = listToTree(list, item.id)
		if (children.length > 0) {
			return {
				...item,
				children
			}
		} else {
			return {
				...item
			}
		}
	})
}

